package eg.ci.mvn.service.core.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ShowVisitUrl
 * server.show-visit-url
 */
@Slf4j
@Component
public class VisitUrlPrinter implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        visitUrlPrinter(event.getApplicationContext().getEnvironment());
    }

    public void visitUrlPrinter(Environment env) {
        boolean enable = env.getProperty("server.visit-url-printer", boolean.class, true);
        if (enable) {
            final String port = env.getProperty("server.port", "8080");
            final String path = env.getProperty("server.servlet.context-path", "");

            String url = getLocalIp4Address().stream()
                    .map(ip -> "http://" + ip + ":" + port + path )
                    .collect(Collectors.joining(","));


            log.info("\n----------------------------------------------------------\n\t" +
                    "Application  is running! Access URLs:\n\t" +
                    "Local访问网址: \t\thttp://127.0.0.1:" + port + path + "\n\t" +
                    "External访问网址: \t" + url + "\n\t" +
                    "Doc访问网址: \t\t\t" + url + "/doc.html" + "\n" +
                    "----------------------------------------------------------");
        }
    }

    public static Set<String> getLocalIp4Address() {
        Set<String> result = new HashSet<>();
        List<Inet4Address> list = null;
        try {
            list = getLocalIp4AddressFromNetworkInterface();
            list.forEach(d -> {
                result.add(d.toString().replaceAll("/", ""));
            });
        } catch (Exception e) {
            //LoggerManager.systemLogger.error("getLocalIp4Address Exception", e);
        }
        return result;
    }

    /*
     * 获取本机所有网卡信息   得到所有IPv4信息
     * @return Inet4Address>
     */
    public static List<Inet4Address> getLocalIp4AddressFromNetworkInterface() throws SocketException {
        List<Inet4Address> addresses = new ArrayList<>(8);
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        if (networkInterfaces == null) {
            return addresses;
        }
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (inetAddress instanceof Inet4Address &&  false == inetAddress.isLoopbackAddress()) {
                    addresses.add((Inet4Address) inetAddress);
                }
            }
        }
        return addresses;
    }


}
